<template>
  <div>
    <!--pc  人才啊-->
    <el-dialog :visible.sync="visible" append-to-body width="33%">
      <p style="text-align: center;" class="map">新增</p>
      <div style="display: flex;align-items: center;margin-bottom: 10px;">
        <span style="display: inline-block;width: 78px;text-align: right;">盘点仓库：</span>
        <el-select @change="findRepStockAndSet" clearable v-model="form.repositoryId" filterable placeholder="仓库">
          <el-option v-for="item in warehouseList" :key="item.value" :label="item.repositoryName" :value="item.id">
          </el-option>
        </el-select>
      </div>
      <div style="display: flex;align-items: center;margin-bottom: 10px;">
        <span style="display: inline-block;width: 78px;text-align: right;">物料编码：</span>
        <el-select clearable v-model="form.materailBasicInfoId" placeholder="请输入物料编码" @change="findRepStockAndSet"
                   filterable
                   remote
                   reserve-keyword
                   :remote-method="queryByMaterialNumber"
                   :loading="loading">
          <el-option
            v-for="item in materiaOptions"
            :key="item.id"
            :label="item.materialNumber"
            :value="item.id">
          </el-option>
        </el-select>
      </div>
      <div style="display: flex;align-items: center;margin-bottom: 10px;">
        <span style="display: inline-block;width: 90px;text-align: right;">物料描述：</span>
        <el-input  disabled   v-model="form.materialName"></el-input>
      </div>
      <div style="display: flex;align-items: center;margin-bottom: 10px;">
        <span style="display: inline-block;width: 90px;text-align: right;">库存数量：</span>
        <el-input  disabled   v-model="form.stockAmount"></el-input>
      </div>
      <div style="display: flex;align-items: center;margin-bottom: 10px;">
        <span style="display: inline-block;width: 90px;text-align: right;">单价：</span>
        <el-input  disabled  v-model="form.singlePrice"></el-input>
      </div>
      <div style="display: flex;align-items: center;margin-bottom: 10px;" >
        <span style="display: inline-block;width: 90px;text-align: right;">盘点数量：</span>
        <el-input type="number" v-model="form.checkQut" @input="caluteDiff"></el-input>
      </div>
      <div style="display: flex;align-items: center;margin-bottom: 10px;">
        <span style="display: inline-block; width: 90px;text-align: right;">差值：</span>
        <el-input type="number" v-model="form.differenceQut"></el-input>
      </div>
      <div style="display: flex;align-items: center;margin-bottom: 10px;">
        <span style=" display: inline-block; width: 90px; text-align: right;">盘点情况：</span>
        <el-input v-model="form.checkRemark"></el-input>
      </div>
      <div style="display: flex;align-items: center;margin-bottom: 10px;">
        <span style="display: inline-block;width: 78px;text-align: right;">盘点日期：</span>
        <el-date-picker
          v-model="form.checkTime" value-format="yyyy-MM-dd"
          type="date"
          placeholder="选择日期">
        </el-date-picker>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="global-button" round type="primary" @click="visible = false">关闭</el-button>
        <el-button class="global-button" round type="primary" @click="submitLine">确认</el-button>
      </span>
    </el-dialog>
    <!--手机-->
    <el-dialog title="新增" :visible.sync="visibleMobile" append-to-body width="90%">
      <div class="form-item">
        <div>盘点仓库：</div>
        <el-select @change="findRepStockAndSet" clearable v-model="form.repositoryId" filterable placeholder="仓库">
          <el-option v-for="item in warehouseList" :key="item.value" :label="item.repositoryName" :value="item.id">
          </el-option>
        </el-select>
      </div>
      <div class="form-item">
        <div >物料编码：</div>
        <el-select clearable v-model="form.materailBasicInfoId" placeholder="请输入物料编码" @change="findRepStockAndSet"
                   filterable
                   remote
                   reserve-keyword
                   :remote-method="queryByMaterialNumber"
                   :loading="loading">
          <el-option
            v-for="item in materiaOptions"
            :key="item.id"
            :label="item.materialNumber"
            :value="item.id">
          </el-option>
        </el-select>
      </div>
      <div class="form-item">
        <div >物料描述：</div>
        <el-input  disabled   v-model="form.materialName"></el-input>
      </div>
      <div class="form-item">
        <div >库存数量：</div>
        <el-input  disabled   v-model="form.stockAmount"></el-input>
      </div>
      <div class="form-item">
        <div >单价：</div>
        <el-input  disabled  v-model="form.singlePrice"></el-input>
      </div>
      <div  class="form-item">
        <div >盘点数量：</div>
        <el-input type="number" v-model="form.checkQut" @input="caluteDiff"></el-input>
      </div>
      <div class="form-item">
        <div >差值：</div>
        <el-input type="number" v-model="form.differenceQut"></el-input>
      </div>
      <div class="form-item">
        <div >盘点情况：</div>
        <el-input v-model="form.checkRemark"></el-input>
      </div>
      <div class="form-item">
        <div>盘点日期：</div>
        <el-date-picker
          v-model="form.checkTime" value-format="yyyy-MM-dd"
          type="date"
          placeholder="选择日期">
        </el-date-picker>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="global-button" round type="primary" @click="visibleMobile = false">关闭</el-button>
        <el-button class="global-button" round type="primary" @click="submitLine">确认</el-button>
      </span>
    </el-dialog>

    <div class="" v-if="!isMobile">
    <el-card v-if="contentView">
      <el-row>
        <el-col :span="12">
          <Searchmodule :placeholder="placeholder" @seacherKey="seacher"></Searchmodule>
        </el-col>
        <el-col :span="12" style="text-align: right;">
         <div>
           <!-- <el-button type="primary" icon="el-icon-download" >导入</el-button>
            <el-button type="primary" icon="el-icon-upload2" >导出</el-button> -->
           <el-button  type="primary" icon="el-icon-download" @click="downloadTemplate">下载导入模板</el-button>
           <el-button    type="primary" icon="el-icon-download" @click="addImoprt">新增导入</el-button>
            <el-button type="primary" icon="el-icon-plus" @click="add(0)">添加</el-button>
         </div>
        </el-col>
      </el-row>
      <!--表格-->
      <el-table :row-style="{height: '10px'}" :cell-style="{padding:'5px'}" :data="tableData" border v-loading="loading">
        <el-table-column type="index" label="序号" v-if="false" align="center" width="50"   :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column prop="repositoryName" label="仓库名称" align="center"   :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column prop="materailNumber" :show-overflow-tooltip="true" label="物料编号"  align="center" >
        </el-table-column>
        <el-table-column prop="materailName" :show-overflow-tooltip="true" label="物料描述" align="center" >
        </el-table-column>
        <el-table-column prop="checkQut" label="盘点数量" align="center"   :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column prop="checkRemark" label="盘点情况" align="center"  :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column prop="stockQut" label="库存数量" align="center"   :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="differenceQut" label="差值" align="center"   :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column prop="checkTime" label="盘点时间" align="center"   :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{scope.row.checkTime | formatTime}}</span>
          </template>
        </el-table-column>
        <!--<el-table-column prop="materailName" label="物料名称" align="center" >-->
        <!--</el-table-column>-->

        <el-table-column label="操作" align="center" width="180"   >
          <template slot-scope="scope">
            <div class="optBtn-box">
              <el-button type="text" icon="el-icon-edit" @click="Delete(scope.row)">删除</el-button>
            </div>
<!--            <el-button type="text" icon="el-icon-tickets" @click="operationView(scope.row)">编辑</el-button>-->

            <!-- <el-button type="primary" icon="el-icon-delete" :loading="scope.row.loading" @click="operationView(2,scope.row)">删除</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <el-pagination style="text-align: center;" :disabled="loading" @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNo" :page-sizes="[25,50]" :page-size="queryInfo.pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <submitForm v-else @closeView="closeView" @refresh="refreshTable"></submitForm>

    <el-dialog :visible.sync="importVisible" append-to-body width="30%">
      <p style="text-align: center;" class="map">新增导入</p>
      <el-form :model="importForm">
        <el-form-item label="导入的文件" prop="fileName">
          <el-upload   style="margin: 0 10px;" :action="importUrl+'import/uploadExcel'"
                       :on-success="uploadSuccessHandler"
                       :on-error="uploadFailHandler"
                       :before-upload="beforeUpload"
                       :file-list="fileList"
                       multiple
                       name="excel" :show-file-list="true" :headers="headers">
            <el-button  type="primary" icon="el-icon-download">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">上传EXCEL文件</div>
          </el-upload>

        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button class="global-button" round type="primary" @click="importVisible = false">关闭</el-button>
        <el-button class="global-button" round type="primary" @click="submitImport">提交</el-button>
      </span>
    </el-dialog>

  </div>
  <!-- 手机 -->
  <div class="mobile-box" v-else>
    <el-row>
      <el-col :span="24"  class="mobile-seacher-box">
        <Searchmodule :placeholder="placeholder" @seacherKey="seacher"></Searchmodule>
      </el-col>
      <el-col :span="24"  class="mobile-seacher-box">
        <el-button type="primary" icon="el-icon-plus" @click="add(1)">添加</el-button>
      </el-col>
    </el-row>
    <div >
      <ul v-if="tableData.length" v-loading="loading">
        <li class="list-item" v-for="item in tableData" :key="item.id">
          <el-card>
            <el-col :span="24">
              <div>仓库名称：{{ item.repositoryName }}</div>
            </el-col>
            <el-col :span="24">
              <div>物料描述：{{ item.materailName }}</div>
            </el-col>
            <el-col :span="24">
              <div>物料编号：{{ item.materailNumber }}</div>
            </el-col>
            <el-col :span="24">
              <div>盘点数量：{{ item.checkQut }}</div>
            </el-col>
            <el-col :span="24">
              <div>盘点情况：{{ item.checkRemark }}</div>
            </el-col>
            <el-col :span="24">
              <div>库存数量：<span >{{ item.stockQut }}</span></div>
            </el-col>
            <el-col :span="24">
              <div>差值：{{ item.differenceQut }}</div>
            </el-col>
            <el-col >
              <div>盘点时间：{{item.checkTime | formatTime}}</div>
            </el-col>
          </el-card>
        </li>
        <el-pagination
          v-if="total >= queryInfo.pageSize"
          style="text-align: center; width: 90%; overflow: auto"
          :disabled="loading"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pageNo"
          :page-sizes="[25, 50]"
          :page-size="queryInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </ul>
      <div v-if="!tableData.length" class="no-data">
        <img :src="require('../../../assets/noData.jpg')" />
      </div>
    </div>
    <!--详情-->
    <!--<el-dialog :modal-append-to-body="false" :close-on-click-modal="false" @close="closeDetailFun" title="详情" :visible.sync="showDetail" width="90%" class="detail-box">-->
      <!--<mobileDetail :detailData="detailData"></mobileDetail>-->
    <!--</el-dialog>-->
  </div>
  </div>
</template>

<script>
import { applyImport, downloadTemplateByType } from '@/api/importApply.js'
import { getWarehouseList, findRepStock } from '@/api/materialScience/warehousingApplication.js'
import submitForm from './components/submitForm.vue'
import { getMaterialAll, findByCanCheckMaterail } from '@/api/purchase.js'
import { mapState } from 'vuex'
import { getInventoryCheckingDelete, getInventoryCheckingAdd, getInventoryCheckingList, getInventoryCheckingEdit } from '@/api/inventoryManagement.js'
let $this = null
export default {
  name: 'inventoryChecking',
  components: {
    submitForm
  },
  computed: {
    ...mapState(['authList'])
  },
  data () {
    return {
      contentView: true,
      placeholder: '材料名称',
      loading: false,
      queryInfo: {
        pageNo: 1,
        pageSize: 25,
        materialName: '',
        materialNumber: ''
      },
      total: 2,
      tableData: [],
      visible: false,
      materailInfoValue: null,
      materiaOptions: [],
      form: {
        repositoryId: '',
        singlePrice: 0,
        checkQut: 0,
        checkRemark: '',
        stockAmount: 0,
        differenceQut: 0,
        checkTime: new Date(),
        materialName: '',
        stockRepositoryId: ''
      },
      repositoryNames: [],
      warehouseList: [],
      importVisible: false,
      importForm: {
        importType: 6,
        fileName: ''
      },
      fileList: [],
      importUrl: this.importUrl,
      headers: {
        apiKey: window.sessionStorage.getItem('token')
      },
    //手机
    detailData:{},
    isMobile:false,
      visibleMobile:false
    }
  },
  created () {
    $this = this
    if (this.$utils.isMobile()) {
      this.isMobile = true
    }
    this.getList()
    getWarehouseList().then(res => {
      this.warehouseList = res.data.data
    })
  },
  methods: {
    caluteDiff () {
      console.log(1111)
      $this.form.differenceQut = $this.form.checkQut - $this.form.stockAmount
    },
    downloadTemplate () {
      $this.isDown = true
      const ttt = {
        type: 6
      }
      downloadTemplateByType(ttt).then(res => {
        $this.isDown = false
        $this.downloadFile(res, '库存盘点导入模板')
      }).catch(err => {
        $this.isDown = false
        return $this.$message.error('导出文件错误')
      })
    },
    addImoprt () {
      this.importVisible = true
    },
    submitImport () {
      if (!$this.importForm.fileName) {
        $this.$message({
          type: 'error',
          message: '文件不能为空',
          showClose: true
        })
        return
      }
      $this.isDown = true
      applyImport($this.importForm).then(res => {
        if (res.headers['content-type'] && res.headers['content-type'].indexOf('multipart/form-data') >= 0) {
          $this.isDown = false
          $this.downloadFile(res, '错误信息')
          this.importVisible = false
          return
        }

        $this.isDown = false
        // console.log(res)
        if (res.headers['content-type'] && res.headers['content-type'].indexOf('application/json') >= 0) {
          $this.$message({
            type: 'error',
            message: '导入失败,请检查审批配置',
            showClose: true
          })
          return
        }
        $this.$message({
          type: 'success',
          message: '提交成功',
          showClose: true
        })
        this.importVisible = false
        $this.$emit('refresh')
      })
    },
    // 导入成功触发
    beforeUpload (file) {
      this.$loading({
        lock: true,
        text: '正在上传...',
        spinner: 'el-icon-loading'
      })
    },
    // 导入成功触发
    uploadSuccessHandler (response, file, fileList) {
      this.$loading().close()
      if (response.success) {
        $this.$message({
          type: 'success',
          message: '上传成功,请提交审批',
          showClose: true
        })
        $this.importForm.fileName = response.data.fileName
        $this.importForm.originFileName = response.data.originFileName
        $this.fileList = []
        $this.fileList.push({ name: response.data.originFileName, url: '' })
        // this.getPageProcurement()
      } else {
        $this.$message({
          type: 'error',
          message: response.message,
          showClose: true
        })
        $this.fileList = []
      }
    },
    uploadFailHandler () {
      this.$loading().close()
      $this.$message.error('上传失败')
    },

    findRepStockAndSet () {
      findRepStock(this.form).then(res => {
        console.log(res)
        console.log(res.data.data.materialName)
        $this.form.materialName = res.data.data.materialName
        $this.form.singlePrice = res.data.data.singlePrice
        $this.form.stockAmount = res.data.data.balance
        $this.form.stockRepositoryId = res.data.data.stockRepositoryId
        $this.caluteDiff()
      })
    },
    queryMaterail (queryWord) {
      // this.materiaOptions=[]
      // this.queryInfo.materialName=queryWord
      // getMaterialAll(this.queryInfo).then(res => {
      //   this.materiaOptions = res.data.data.records && res.data.data.records
      // })
    },

    queryByMaterialNumber (queryWord) {
      this.materiaOptions = []
      this.queryInfo.materialNumber = queryWord
      findByCanCheckMaterail(this.queryInfo).then(res => {
        this.materiaOptions = res.data.data && res.data.data
      })
    },

    authFilter (code) {
      let flag = false
      if (this.authList.length) {
        this.authList.forEach(item => {
          if (item.resourceCode == code) {
            flag = true
          }
        })
      }
      return flag
    },
    operationView (row) {
      this.visible = true
      this.materiaOptions = []
      this.queryInfo.materialNumber = row.materailNumber
      findByCanCheckMaterail(this.queryInfo).then(res => {
        this.materiaOptions = res.data.data && res.data.data
      })

      this.form = Object.assign({}, row)

      this.form.materialName = row.materailName
      this.form.stockAmount = row.stockQut
    },
    add (id) {
      this.form.id = null
      id === 0 ? ( this.visible = true):( this.visibleMobile = true)
      $this.form.checkTime = new Date()
    },
    Delete (row) {
      this.$loading()
      getInventoryCheckingDelete(row.id).then(res => {
        this.$loading().close()
        const { data } = res
        if (data.code == '200') {
          this.form = {}
          this.getList()
          this.$message.success('删除成功')
        } else {
          this.$message.success(data.message)
        }
      })
    },
    submitLine () {
      this.$loading()
      if (this.form.id) {
        getInventoryCheckingEdit(this.form).then(res => {
          this.$loading().close()
          const { data } = res
          if (data.code == '200') {
            this.form = {}
            this.getList()
            this.$message.success('修改成功')
          } else {
            this.$message.error(data.message)
          }
        })
      } else {
        getInventoryCheckingAdd(this.form).then(res => {
          this.$loading().close()
          const { data } = res
          if (data.code == '200') {
            this.form = {}
            this.getList()
            this.$message.success('新增成功')
          } else {
            this.$message.error(data.message)
          }
        })
      }
      this.visibleMobile = false
      this.visible = false
    },
    getList () {
      $this.loading = true
      getInventoryCheckingList($this.queryInfo).then(res => {
        $this.loading = false
        $this.tableData = res.data.data.records
        $this.total = res.data.data.total
      }).catch(err => {
        $this.loading = false
        return $this.$message.error(err.message)
      })
    },
    handleCurrentChange (val) {
      $this.queryInfo.pageNo = val
      this.getList()
    },
    handleSizeChange (size) {
      $this.queryInfo.pageSize = size
      this.getList()
    },
    seacher (key) {
      this.queryInfo.materailName = key
      this.getList()
    },
    // 返回table
    closeView () {
      $this.contentView = true
    },
    refreshTable () {
      $this.contentView = true
    },
    downloadFile (res, name) {
      const blob = new Blob([res.data])
      const fileName = name + '.xlsx'
      const elink = document.createElement('a')
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href)
      document.body.removeChild(elink)
    }
  }
}
</script>
<style lang="scss" scoped>
  .form-item{
   div{
     font-size: 15px;
     margin-bottom: 5px;
     &+div{
       margin: 5px 0;
     }
   }
  }
  @mixin box-width {
    width: 90%;
    margin: 10px auto;
  }
  .mobile-box {
    position: relative;
    .el-row{
      display: flex;
      flex-direction: column;
    }
    .btn-data {
      @include box-width;
    }
    .mobile-seacher-box{
      width: 90%;
      margin: 10px auto;
    }
    ul {
      padding: 0;
      & > li {
        @include box-width;
        list-style-type: none;
        .btn-box {
          text-align: right;
          margin-bottom: 10px;
        }
        .el-col {
          margin: 5px 0;
        }
      }
    }
    .no-data {
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      img {
        width: 400px;
      }
    }
    .addForm {
      .el-input,
      .el-select,
      .el-textarea{
        width: 100%;
      }
      .el-form-item{
        padding: 0 20px;
        margin-bottom: 10px;
        .btn-box{
          width: 100%;
          text-align: center;
          margin: 20px 0;
          .el-button{
            width: 45%;
          }
        }
      }
    }
    .detail-box,.materail-box{
      overflow: auto;
      div{
        margin: 5px 0;
        font-size: 15px;
      }
    }

  }
</style>
<style >
  .el-table th{
    padding: 0;
    line-height: normal;
  }
  .el-select,.el-date-editor{
    width: 100%;
  }
</style>
